package com.atguigu.gmall.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.vo.LoginSuccessVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
* @author lfy
* @description 针对表【user_info(用户表)】的数据库操作Service实现
* @createDate 2022-12-15 09:40:04
*/
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
    implements UserInfoService{

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public LoginSuccessVo login(UserInfo info) {

        //响应结果以json方式交给前端，他会自动处理。
        //（1）放大域名  （2）其他有效
        LoginSuccessVo resp = new LoginSuccessVo();



        String loginName = info.getLoginName();
        String passwd = MD5.encrypt(info.getPasswd());

        //1、去数据库查询登录用户
        UserInfo entity = lambdaQuery()
                .eq(UserInfo::getLoginName, loginName)
                .eq(UserInfo::getPasswd, passwd)
                .one();

        //任何业务不预期的行为直接抛异常，由全局异常处理来进行捕获统一返回
        if(entity == null){
            throw new GmallException(ResultCodeEnum.LOGIN_ERROR);
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        resp.setToken(token);
        resp.setUserId(entity.getId());
        resp.setNickName(entity.getNickName());

        //2、服务端要共享token与用户信息的对应数据
        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER +token, JSON.toJSONString(entity),7, TimeUnit.DAYS);

        //3、给前端返回完整数据
        return resp;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER+token);
    }
}




